package observer;

import java.io.Serializable;
import java.util.ArrayList;

/**
 * These ints can be observed by {@link IntObserver}s, i.e. the observers will be notified of any changes.
 *
 * @author Neil Dickson
 */
public final class ObservedInt implements Copiable<ObservedInt>, Serializable {
	private int						value;
	private ArrayList<IntObserver>	observers;

	public ObservedInt(int i) {
		value = i;
		observers = null;
	}

	public synchronized void addObserver(IntObserver observer) {
		if (observer==null) {
			throw new NullPointerException();
		}
		if (observers==null) {
			observers = new ArrayList<IntObserver>();
		}
		if (!observers.contains(observer)) {
			observers.add(observer);
		}
	}
	public synchronized void removeObserver(IntObserver observer) {
		if (observers!=null && observers.contains(observer)) {
			observers.remove(observer);
		}
	}

	public int get() {
		return value;
	}
	public void set(int i) {
		set(null,i);
	}
	public void set(IntObserver culprit,int i) {
		value = i;
		updateAllBut(culprit);
	}

	public String toString() {
		return Integer.toString(value);
	}

	public ObservedInt copy() {
		return new ObservedInt(value);
	}

	private void updateAllBut(IntObserver culprit) {
		if (observers!=null) {
			for (IntObserver observer : observers) {
				if (observer!=culprit) {
					observer.valueChanged(this);
				}
			}
		}
	}

	public boolean equals(Object obj) {
		return (obj!=null) && (obj instanceof ObservedInt) && ((ObservedInt)obj).value==value;
	}

	public int hashCode() {
		return value;
	}
}
